﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Framework;
using VAdvantage.Controls;
using VAdvantage.Utility;
using VAdvantage.Classes;
using VAdvantage.Model;
using System.Text;
using System.Data.SqlClient;
using System.Linq;


namespace VAdvantage.Search
{
    public class InfoInOut : Info
    {
        #region PrivateVariable

        string _documentNo = "";
        string _description = "";
        string _POReference = "";
        System.DateTime? dateFrom = null;
        System.DateTime? dateTo = null;
        string amtFrom = "";
        string amtTo = "";
        bool isSoTrx = false;
        object bpValue = null;
        string _queryValue = "";

        int bp;
        private ToolTip tooltip = new ToolTip();
        //on value change of datetime pickker
        private bool _dateTimeFromCheck = false;
        private bool _dateTimeToCheck = false;
        //  Static Info
        private VLabel lblDocumentNo = new VLabel();
        private VTextBox txtDocumentNo = new VTextBox();
        private VLabel lblDescription = new VLabel();
        private VTextBox txtDescription = new VTextBox();
        private VLabel lblPOReference = new VLabel();
        private VTextBox txtPOReference = new VTextBox();
        private VLabel lblBPartner_ID = new VLabel();
        private VTextBoxButton vBPartner_ID;
        private VLabel lblDateFrom = new VLabel();
        private VAdvantage.Controls.VDatePicker dtpDateFrom = new VAdvantage.Controls.VDatePicker();
        private VLabel lblDateTo = new VLabel();
        private VAdvantage.Controls.VDatePicker dtpDateTo = new VAdvantage.Controls.VDatePicker();
        private VCheckBox chkIsSOTrx = new VCheckBox();
        // Array of Column Info    
        private static Info_Column[] _inOutLayout = {
		new Info_Column("M_InOut_ID", "i.M_InOut_ID", typeof(IDColumn)),
		new Info_Column(Msg.Translate(Utility.Envs.GetContext(), "C_BPartner_ID"), "(SELECT Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=i.C_BPartner_ID)", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "MovementDate"), "i.MovementDate", typeof(DateTime)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "DocumentNo"), "i.DocumentNo", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "Description"), "i.Description", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "POReference"), "i.POReference", typeof(String)),
		new Info_Column(Msg.Translate(Envs.GetContext(), "IsSOTrx"), "i.IsSOTrx", typeof(Boolean))
	};
        #endregion


        /// <summary>
        /// Detail Protected Contructor
        /// </summary>
        /// <param name="frame"> parent frame</param>
        /// <param name="modal">modal</param>
        /// <param name="WindowNo">window no</param>
        /// <param name="value">query value</param>
        /// <param name="multiSelection">multiple selections</param>
        /// <param name="whereClause">where clause</param>
        public InfoInOut(Object frame, bool modal, int WindowNo, String value, bool multiSelection, String whereClause)
            : base(frame, modal, WindowNo, "i", "M_InOut_ID", multiSelection, whereClause)
        {
            base.SetTitle(Msg.GetMsg(Envs.GetContext(), "InfoInOut", true));
            try
            {
                _queryValue = value;
                StatInit();
                _LoadedOK = InitInfo();
            }
            catch
            {
                return;
            }
        }

        private bool InitInfo()
        {
            //put in invok function
            //Context ctx = Envs.GetContext();
            ////  Set Defaults
            //String bp = ctx.GetContext(_WindowNo, "C_BPartner_ID");
            //if (bp != null && bp.Length != 0)
            //{
            //    vBPartner_ID.SetValue(bp);
            //}

            //  prepare table
            StringBuilder where = new StringBuilder("i.IsActive='Y'");
            if (_whereClause.Length > 0)
            {
                where.Append(" AND ").Append(Util.Replace(_whereClause, "M_InOut.", "i."));
            }
            PrepareTable("M_InOut i", where.ToString(), "2,3,4");
            return true;
        }

        private void StatInit()
        {
            InfoSetting();

            Lookup _value = null;

            SetBusy(true);
                
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 3499, DisplayType.Search);
                string isSOTrxValue = Msg.GetElement(Envs.GetContext(), "IsSOTrx");
                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(_value, isSOTrxValue));
            });

            lblDocumentNo.Content = Msg.Translate(Envs.GetContext(), "DocumentNo");
            lblDescription.Content = Msg.Translate(Envs.GetContext(), "Description");
            lblPOReference.Content = Msg.Translate(Envs.GetContext(), "POReference");
            lblBPartner_ID.Content = Msg.Translate(Envs.GetContext(), "BPartner");
            lblDateFrom.Content = Msg.Translate(Envs.GetContext(), "MovementDate");
            lblDateTo.Content = "-";

            chkIsSOTrx.IsChecked = true;

            //Level Controls alignment
            lblDocumentNo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDocumentNo.Margin = new Thickness(0, 0, 5, 0);

            lblDescription.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDescription.Margin = new Thickness(0, 0, 5, 0);

            lblPOReference.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblPOReference.Margin = new Thickness(0, 0, 5, 0);

            lblBPartner_ID.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblBPartner_ID.Margin = new Thickness(0, 0, 5, 0);

            lblDateFrom.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDateFrom.Margin = new Thickness(0, 0, 5, 0);

            lblDateTo.HorizontalAlignment = System.Windows.HorizontalAlignment.Right;
            lblDateTo.Margin = new Thickness(0, 0, 5, 0);

            chkIsSOTrx.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
            chkIsSOTrx.Margin = new Thickness(0, 0, 5, 0);

            //Document NO--LIne1
            Grid.SetColumn(lblDocumentNo, 0);
            Grid.SetRow(lblDocumentNo, 0);
            this.tablePanel.Children.Add(lblDocumentNo);

            txtDocumentNo.Height = HEIGHT;
            txtDocumentNo.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            Grid.SetColumn(txtDocumentNo, 1);
            Grid.SetRow(txtDocumentNo, 0);
            this.tablePanel.Children.Add(txtDocumentNo);

            Grid.SetColumn(lblBPartner_ID, 2);
            Grid.SetRow(lblBPartner_ID, 0);
            this.tablePanel.Children.Add(lblBPartner_ID);



            Grid.SetColumn(chkIsSOTrx, 5);
            Grid.SetRow(chkIsSOTrx, 0);
            this.tablePanel.Children.Add(chkIsSOTrx);

            //Description---Line2
            Grid.SetColumn(lblDescription, 0);
            Grid.SetRow(lblDescription, 1);
            this.tablePanel.Children.Add(lblDescription); ;

            txtDescription.Height = HEIGHT;
            Grid.SetColumn(txtDescription, 1);
            Grid.SetRow(txtDescription, 1);
            this.tablePanel.Children.Add(txtDescription);

            Grid.SetColumn(lblDateFrom, 2);
            Grid.SetRow(lblDateFrom, 1);
            this.tablePanel.Children.Add(lblDateFrom);

            dtpDateFrom.Height = HEIGHT;
            Grid.SetColumn(dtpDateFrom, 3);
            Grid.SetRow(dtpDateFrom, 1);
            this.tablePanel.Children.Add(dtpDateFrom);

            //Date to
            Grid.SetColumn(lblDateTo, 4);
            Grid.SetRow(lblDateTo, 1);
            this.tablePanel.Children.Add(lblDateTo);

            dtpDateTo.Height = HEIGHT;
            Grid.SetColumn(dtpDateTo, 5);
            Grid.SetRow(dtpDateTo, 1);
            this.tablePanel.Children.Add(dtpDateTo);

            //PORefrence
            Grid.SetColumn(lblPOReference, 0);
            Grid.SetRow(lblPOReference, 2);
            this.tablePanel.Children.Add(lblPOReference);


            txtPOReference.Height = HEIGHT;
            Grid.SetColumn(txtPOReference, 1);
            Grid.SetRow(txtPOReference, 2);
            this.tablePanel.Children.Add(txtPOReference);

            
            txtDocumentNo.TextChanged += new TextChangedEventHandler(txtDocumentNo_TextChanged);
            txtDescription.TextChanged += new TextChangedEventHandler(txtDescription_TextChanged);
            txtPOReference.TextChanged += new TextChangedEventHandler(txtPOReference_TextChanged);

            this.chkIsSOTrx.Checked += new RoutedEventHandler(chkIsSOTrx_CheckedChanged);
            this.chkIsSOTrx.Unchecked += new RoutedEventHandler(chkIsSOTrx_CheckedChanged);

            this.dtpDateFrom.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateFrom_SelectedDateChanged);
            this.dtpDateTo.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(dtpDateTo_SelectedDateChanged);

            //key event handling only on text boexes
            txtDocumentNo.KeyDown += new KeyEventHandler(KeyEvents);
            txtDescription.KeyDown += new KeyEventHandler(KeyEvents);
            txtPOReference.KeyDown += new KeyEventHandler(KeyEvents);
            vdgvRecords.AutoGeneratingColumn += new EventHandler<DataGridAutoGeneratingColumnEventArgs>(vdgvRecords_AutoGeneratingColumn);
        }

        private void InvoKFunction(Lookup _value, string isSOTrxValue)
        {
            vBPartner_ID = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);
            //check box1
            chkIsSOTrx.Content = isSOTrxValue;
                //tooltip.SetToolTip(chkIsSOTrx, Msg.GetElement(Envs.GetContext(), "IsSOTrx"));

            Grid.SetColumn(vBPartner_ID, 3);
            Grid.SetRow(vBPartner_ID, 0);
            this.tablePanel.Children.Add(vBPartner_ID);

            Context ctx = Envs.GetContext();
            //  Set Defaults
            String bp = ctx.GetContext(_WindowNo, "C_BPartner_ID");
            if (bp != null && bp.Length != 0)
            {
                vBPartner_ID.SetValue(bp);
            }
            var count = 0;
            if (vdgvRecords.ItemsSource != null)
            {
                count = vdgvRecords.ItemsSource.OfType<object>().Count();
            }
            base.SetStatusMsg(count.ToString() + " " + Msg.GetMsg(Envs.GetContext(), "SearchRows_EnterQuery", true));
            if (_queryValue != null && _queryValue.Length > 0)
            {
                txtDocumentNo.Text = _queryValue.ToString();
                ExecuteQuery();
            }

            SetBusy(false);

            txtDocumentNo.Focus();

        }

        void txtPOReference_TextChanged(object sender, TextChangedEventArgs e)
        {
            _POReference = txtPOReference.Text.Trim();
        }

        void txtDescription_TextChanged(object sender, TextChangedEventArgs e)
        {
            _description = txtDescription.Text.Trim();
        }

        void txtDocumentNo_TextChanged(object sender, TextChangedEventArgs e)
        {
            _documentNo = txtDocumentNo.Text.Trim();
        }

        /// <summary>
        /// Sets the display setting
        /// </summary>
        protected void InfoSetting()
        {
            RowDefinition row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);

            row = new RowDefinition();
            row.Height = new GridLength(0, GridUnitType.Auto);
            row.MinHeight = 30;
            this.tablePanel.RowDefinitions.Add(row);


            ColumnDefinition column = new ColumnDefinition();
            column.Width = new GridLength(30, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(50, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);


            column = new ColumnDefinition();
            column.Width = new GridLength(33, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(50, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(4, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);

            column = new ColumnDefinition();
            column.Width = new GridLength(45, GridUnitType.Star);
            this.tablePanel.ColumnDefinitions.Add(column);
        }

        protected override Info_Column[] GetInfoColumns()
        {
            return _inOutLayout;
        }

        /// <summary>
        /// Construct SQL Where Clause and define parameters.
        /// (setParameters needs to set parameters)
        /// Includes first AND
        /// </summary>
        /// <returns>sql</returns>
        public override String GetSQLWhere()
        {
            StringBuilder sql = new StringBuilder();
            if (_documentNo.Length > 0)
            {
                sql.Append(" AND UPPER(i.DocumentNo) LIKE @param1");
            }
            if (_description.Length > 0)
            {
                sql.Append(" AND UPPER(i.Description) LIKE @param2");
            }
            if (_POReference.Length > 0)
            {
                sql.Append(" AND UPPER(i.POReference) LIKE @param3");
            }
            //
            if (bpValue != null && bpValue != DBNull.Value)
            {
                sql.Append(" AND i.C_BPartner_ID=@param4");
            }
            //date check
            if ((dateFrom != null || dateTo != null))
            {
                if (!_dateTimeFromCheck && _dateTimeToCheck)
                {
                    sql.Append(" AND TRUNC(i.MovementDate,'DD') <= @param6");
                }
                else if (_dateTimeFromCheck && !_dateTimeToCheck)
                {
                    sql.Append(" AND TRUNC(i.MovementDate,'DD') >= @param5");
                }
                else if (_dateTimeFromCheck && _dateTimeToCheck)
                {
                    sql.Append(" AND TRUNC(i.MovementDate,'DD') BETWEEN @param5 AND @param6");
                }
            }

            String chekSelect = isSoTrx == true ? "Y" : "N";
            sql.Append(" AND i.IsSOTrx=" + "'" + chekSelect + "'");

            //log.finer(sql.toString());
            return sql.ToString();
        }

        /// <summary>
        /// Set Parameters for Query.
        /// (as defined in getSQLWhere)
        /// </summary>
        /// <param name="param">statement</param>
        /// <param name="forCount">for counting records</param>
        public override void SetParameters(out SqlParameter[] param, bool forCount)
        {
            String docNo = GetSQLText(_documentNo);
            String des = GetSQLText(_description);
            String orderRef = GetSQLText(_POReference);

            if (bpValue != null)
            {
                bp = Util.GetValueOfInt(bpValue);
            }
            else
            {
                bp = 0;
            }

            int paramcount = 0;
            if (!(docNo.Equals("") || docNo.Equals("%")))
            {
                paramcount++;
            }
            if (!(des.Equals("") || des.Equals("%")))
            {
                paramcount++;
            }
            if (!(orderRef.Equals("") || orderRef.Equals("%")))
            {
                paramcount++;
            }
            if (!(bp.Equals("") || bp.Equals("%") || bp == 0))
            {
                paramcount++;
            }
            //becouse this contain default date
            if (_dateTimeFromCheck)
            {
                paramcount++;
            }
            if (_dateTimeToCheck)
            {
                paramcount++;
            }

            param = new SqlParameter[paramcount];
            int index = 0;
            //	=> Documenet Number
            if (!(docNo.Equals("") || docNo.Equals("%")))
            {
                if (!docNo.EndsWith("%"))
                {
                    docNo += "%";
                }
                param[index++] = new SqlParameter("@param1", docNo);
            }
            //	=> DEscription
            if (!(des.Equals("") || des.Equals("%")))
            {
                if (!des.EndsWith("%"))
                {
                    des += "%";
                }
                param[index++] = new SqlParameter("@param2", des);
            }
            //	=> Order Refrence
            if (!(orderRef.Equals("") || orderRef.Equals("%")))
            {
                if (!orderRef.EndsWith("%"))
                {
                    orderRef += "%";
                }
                param[index++] = new SqlParameter("@param3", orderRef);
            }
            //	=> Busness Partner
            if (!(bp.Equals("") || bp.Equals("%") || bp == 0))
            {
                param[index++] = new SqlParameter("@param4", bp);
                log.Fine("BPartner=" + bp);
            }
            if (dateFrom != null || dateTo != null)
            {
                //	=> Date Ordered From
                if (_dateTimeFromCheck)
                {
                    param[index++] = new SqlParameter("@param5", dateFrom.Value.ToString("dd-MMM-yy"));
                }
                //	=> Date Ordered TO
                if (_dateTimeToCheck)
                {
                    param[index++] = new SqlParameter("@param6", dateTo.Value.ToString("dd-MMM-yy"));
                }
            }

        }


        /// <summary>
        /// Get SQL WHERE parameter
        /// </summary>
        /// <param name="f">field</param>
        /// <returns>sql</returns>
        private String GetSQLText(string f)
        {
            String s = f.ToUpper();
            if (!s.EndsWith("%"))
            {
                s += "%";
            }
            //log.fine("String=" + s);
            return s;
        }

        /// <summary>
        /// Zoom Window
        /// </summary>
        /// <param name="tableName"></param>
        /// <param name="query"></param>
        /// <returns></returns>
        private int GetAD_Window_ID(String tableName, Query query)
        {
            return (ZoomTarget.GetZoomAD_Window_ID(tableName, 0, query.GetWhereClause(), true));
        }

        /// <summary>
        /// Zoom
        /// </summary>
        void Zoom()
        {
            log.Info("InfoInOut.zoom");
            int M_InOut_ID = Convert.ToInt32(GetSelectedRowKey());
            if (M_InOut_ID == null)
            {
                return;
            }
            Query query = new Query("M_InOut");
            query.AddRestriction("M_InOut_ID", Query.EQUAL, M_InOut_ID);
            query.SetRecordCount(1);
            int AD_WindowNo = GetAD_Window_ID("M_InOut", query);
            //zoom(AD_WindowNo, query);
        }

        /// <summary>
        /// Has Zoom
        /// </summary>
        /// <returns>true</returns>
        bool HasZoom()
        {
            return true;
        }

        /// <summary>
        /// On key down event
        /// </summary>
        /// <param name="sender">key</param>
        /// <param name="e">current event</param>
        private void KeyEvents(object sender, KeyEventArgs e)
        {
            isSoTrx = (bool)chkIsSOTrx.IsChecked;
            bpValue = vBPartner_ID.GetValue();
            if (e.Key == Key.Enter)
            {
                ExecuteQuery();
            }
            else if (e.Key == Key.Down)
            {
                vdgvRecords.Focus();
            }
        }

        /// <summary>
        /// Check Click event to show records in grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkIsSOTrx_CheckedChanged(object sender, RoutedEventArgs e)
        {
            isSoTrx = (bool)chkIsSOTrx.IsChecked;
            bpValue = vBPartner_ID.GetValue();
            ExecuteQuery();
        }

        /// <summary>
        /// event to check default value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dtpDateFrom_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeFromCheck = true;
            if (dtpDateFrom.Text.Trim() != "")
            {
                dateFrom = Convert.ToDateTime(dtpDateFrom.Text.Trim());
            }
            else
            {
                dateFrom = null;
            }
        }

        /// <summary>
        /// event to check default value
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dtpDateTo_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            _dateTimeToCheck = true;
            if (dtpDateTo.Text.Trim() != "")
            {
                dateTo = Convert.ToDateTime(dtpDateTo.Text.Trim());
            }
            else
            {
                dateTo = null;
            }
        }

        protected override void bRefresh_Click(object sender, RoutedEventArgs e)
        {
            isSoTrx = (bool)chkIsSOTrx.IsChecked;
            bpValue = vBPartner_ID.GetValue();
            ExecuteQuery();
        }

        void vdgvRecords_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
        {
            foreach (DataGridColumn col in vdgvRecords.Columns)
            {
                if (col.DisplayIndex == 0)
                {
                    col.Visibility = Visibility.Collapsed;
                }
            }
        }
    }
}
